<template>
  <div style="background-color: #f6f6f6">
    <el-row>
      <el-col :span="20" :offset="2">
        <div class="form" style="padding-left: 20px;">
          <el-form :inline="true" :model="answererKeywordToSearch" class="dw-form-inline" size="medium">
            <el-form-item label="答者名">
              <el-input v-model="answererKeywordToSearch" placeholder="请输入要查询的答者名" clearable></el-input>
            </el-form-item>
            <el-form-item style="margin-left: 20px;">
              <el-button type="primary" @click="searchAnswererByKey()">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="table">
          <div class="table-title">
            <el-row :span="24" type="flex" justify="space-between" align="middle">
              <el-col :span="4"><h3>答者管理</h3></el-col>
              <el-col :span="20" style="text-align: right;">
                <el-dropdown @command="handleAdd">
                  <el-button plain type="primary">添加答者<i class="el-icon-arrow-down el-icon--right"></i></el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="0">单独添加</el-dropdown-item>
                    <el-dropdown-item command="1">批量导入</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                <el-button plain type="success" style="height: 42px;margin-left: 20px" @click="showGroups">将选中答者加入群组</el-button>
              </el-col>
            </el-row>
          </div>
          <el-table :data="answererData.slice((currentPage-1)*pageSize,currentPage*pageSize)" stripe style="width: 100%"
                    border @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="序号" width="150" type="index" sortable></el-table-column>
            <el-table-column label="答者名" width="200" prop="username"></el-table-column>
            <el-table-column label="答者电话" width="250" prop="telnumber"></el-table-column>
            <el-table-column label="创建时间" prop="createdDate">
              <template v-slot="scope">
                {{formatDate(scope.row.createdDate)}}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" align="center">
              <template slot-scope="scope">
                <el-tooltip effect="dark" content="修改" placement="top">
                  <el-button size="medium" icon="el-icon-edit" type="primary" circle
                             @click="handleEditClick(scope.$index)"></el-button>
                </el-tooltip>
                <el-tooltip effect="dark" content="删除" placement="top">
                  <el-button size="medium" icon="el-icon-delete" type="danger" circle
                             @click="handleDelete(scope.$index)"></el-button>
                </el-tooltip>
              </template>

            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination
              :page-size="pageSize"
              :current-page="currentPage"
              :total="total"
              :page-sizes="[5,10,20,50]"
              background
              layout="sizes,prev, pager, next"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
            >
            </el-pagination>
          </div>
        </div>
      </el-col>
    </el-row>
    <div>
      <el-dialog title="添加答者" :visible.sync="addDialogFormVisible" style="padding-top: 0px" append-to-body>
        <el-form :model="answererToOperate" :rules="addAnswererRules" label-position="top">
          <el-form-item label="答者名" :label-width="formLabelWidth" prop="name">
            <el-input v-model="answererToOperate.name" clearable placeholder="请输入答者名"></el-input>
          </el-form-item>
          <el-form-item label="答者密码" :label-width="formLabelWidth" prop="password">
            <el-input v-model="answererToOperate.password" clearable show-password placeholder="请输入答者密码"></el-input>
          </el-form-item>
          <el-form-item label="答者电话" :label-width="formLabelWidth" prop="tele">
            <el-input v-model="answererToOperate.tele" clearable placeholder="请输入答者电话"></el-input>
          </el-form-item>
          <el-form-item label="密保问题" :label-width="formLabelWidth" prop="securityQuestionContext">
            <el-input v-model="answererToOperate.securityQuestionContext" clearable placeholder="请输入密保问题" ></el-input>
          </el-form-item>
          <el-form-item label="密保答案" :label-width="formLabelWidth" prop="securityQuestionAnswer">
            <el-input v-model="answererToOperate.securityQuestionAnswer" clearable placeholder="请输入密保答案"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addDialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleAddSubmit()">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div>
      <el-dialog title="批量导入答者" :visible.sync="importDialogFormVisible"
                 style="padding-top: 0px;padding-left:350px;padding-right:350px;width:900px" append-to-body>
        <el-form :model="answererToOperate" label-position="left">
          <el-form-item style="padding-bottom: 20px;padding-left: 120px">
            <el-button type="success" icon="el-icon-download" @click="downloadTemplate()">下载答者信息模板</el-button>
          </el-form-item>
          <el-form-item style="padding-bottom: 20px;padding-left: 25px;padding-right: 100px">
            <el-upload drag limit="1" :auto-upload="false" :action="uploadUrl"
                       :before-upload="beforeUpload" :on-change="fileChange" :on-exceed="exceedFile"
                       accept=".xlsx,.xls" :file-list="fileList">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">请按模板上传Excel文件</div>
            </el-upload>
          </el-form-item>
          <el-form-item style="padding-bottom: 20px;padding-left: 150px">
            <el-button type="success" icon="el-icon-upload" @click="upload()">确认上传</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
    <div>
      <el-dialog title="修改答者信息" :visible.sync="editDialogFormVisible" style="padding-top: 100px" append-to-body>
        <el-form :model="answererToOperate" label-position="left" >
          <el-form-item label="答者名" :label-width="formLabelWidth" style="padding-bottom: 20px">
            <el-input v-model="answererToOperate.name" clearable></el-input>
          </el-form-item>
          <el-form-item label="答者电话" :label-width="formLabelWidth">
            <el-input v-model="answererToOperate.tele" clearable></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editDialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleEditSubmit()">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div>
      <el-dialog title="请选择要加入的群组" :visible.sync="groupDialogTableVisible" style="padding-top: 0px" append-to-body>
        <el-form :inline="true" :model="group" class="dw-form-inline" size="medium">
          <el-form-item label="群组名">
            <el-input v-model="group.groupName" placeholder="请输入要查询的群组" clearable></el-input>
          </el-form-item>
          <el-form-item style="margin-left: 20px;">
            <el-button type="primary" @click="searchGroup">查询群组</el-button>
          </el-form-item>
        </el-form>
        <el-table :data="groupData" border="border" stripe style="width: 100%">
          <el-table-column type="index" width="40"></el-table-column>
          <el-table-column label="群组名称" prop="groupname" width="200"></el-table-column>
          <el-table-column label="详细说明" prop="introduction" width="380"></el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
                <el-button icon="el-icon-plus" size="medium" type="success"
                           @click="addAnswererToGroup(scope.row.groupname)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {searchAnswerer, addAnswerer, modifyAnswerer, deleteAnswerer, addAnswererToGroup, downTemplate, uploadAnswererData} from '../../api/user.js'
import {queryGroupsByKeyword} from "../../api/user/user-group";
import {DateFormat} from "../../utils/common";

export default {
  name: "userHome",
  data() {
    return {
      userInfo: {},
      answererKeywordToSearch: '',
      answererToOperate: {
        id: '',
        name: '',
        password: '',
        tele: '',
        createdDate: '',
        securityQuestionContext: '',
        securityQuestionAnswer: ''
      },
      answererData: [],
      selectedAnswerer: [],
      answererNames: [],
      groupData: [],
      group: {
        groupName: '',
        groupDescription: '',
        id: null,
      },
      pageSize: 5,
      currentPage: 1,
      total: 1,

      fileList: [],

      addDialogFormVisible: false,
      editDialogFormVisible: false,
      importDialogFormVisible: false,
      groupDialogTableVisible: false,

      formLabelWidth: '80px',

      addAnswererRules: {
        name: [
          {required:true, message: '请输入用户名', trigger: 'blur'},
          {min:2,message: '用户名长度至少为两个字符',trigger: 'blur'}
        ],
        password: [
          {required:true, message: '请输入密码', trigger: 'blur'},
          {min:6,message: '密码至少为6位',trigger: 'blur'}
        ],
        tele: [
          {required:true, pattern: /^1[34578]\d{9}$/, message: '请输入中国大陆电话号码', trigger: 'blur'},
        ],
        securityQuestionContext: [
          {required:true, message: '请输入密保问题', trigger: 'blur'},
        ],
        securityQuestionAnswer: [
          {required:true, message: '请输入密保问题答案', trigger: 'blur'},
        ]
      }
    }
  },
  methods: {
    formatDate(date){
      return DateFormat(date)
    },
    searchAnswererByKey() {
      searchAnswerer(this.userInfo.id, this.answererKeywordToSearch).then((response) => {
        // console.log(response)
        this.answererData = response.data.data
        this.total = response.data.data.length
      })
    },
    handleAdd(command) {
      this.cleanAnswererBuffer()
      if (command == '0') {
        //单独添加答者
        this.addDialogFormVisible = true
      }
      if (command == '1') {
        //批量导入答者
        this.importDialogFormVisible = true
      }
    },
    handleAddSubmit() {
      if (this.answererToOperate.name.length < 1
        ||this.answererToOperate.tele.length != 11
        ||this.answererToOperate.password.length < 6) {
        this.$message("请输入合法信息")
        return
      }
      //调用添加答者接口
      addAnswerer(this.answererToOperate.name,this.answererToOperate.password, this.answererToOperate.tele,
        this.answererToOperate.securityQuestionContext,this.answererToOperate.securityQuestionAnswer).then((response) =>{
        console.log(response)
        const httpResult = response.data
        if (httpResult.code === 200) {
          this.$message.success('添加成功，即将刷新数据')
          this.searchAnswererByKey()
        } else {
          this.$message.error('添加答者失败')
        }
      })
      this.addDialogFormVisible = false
    },
    downloadTemplate() {
      window.location.href="http://172.18.28.123:8050/user/getModelExcel";
    },
    exceedFile(files, fileList) {
      this.$message.warning(
        `只能选择1个文件，当前共选择了 ${
          files.length + fileList.length
        } 个`
      );
    },
    fileChange(file) {
      if(this.fileList.length===0){
        this.fileList.push(file.raw);
      }
      console.log("fileList.length:"+this.fileList.length)
    },
    beforeUpload(file) {
      let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
      if (extension !== "xls"&&extension !== "xlsx") {
        this.$message.warning("只能上传后缀是.xls或.xlsx的文件");
      }
    },
    uploadUrl: function (){
      return ''
    },
    upload() {
      if (this.fileList.length === 0) {
        this.$message.warning("请上传文件");
      } else {
        // this.$message(this.fileList[0].name)
        let form = new FormData()
        form.append("file",this.fileList[0])
        uploadAnswererData(form).then((response)=>{
          // console.log(response)
          const httpResult = response.data
          if (httpResult.code === 200) {
            this.$message.success('批量导入成功，即将刷新数据')
            this.importDialogFormVisible = false
            this.searchAnswererByKey()
          } else {
            this.$message.error(httpResult.message)
          }
        })
      }
    },
    handleEditClick(index) {
      this.cleanAnswererBuffer()
      let dataIndex = index + this.pageSize * (this.currentPage - 1)
      this.answererToOperate.id = this.answererData[dataIndex].id
      this.answererToOperate.name = this.answererData[dataIndex].username
      this.answererToOperate.tele = this.answererData[dataIndex].telnumber
      this.answererToOperate.securityQuestionContext = this.answererData[dataIndex].securityQuestionContext
      this.answererToOperate.securityQuestionAnswer = this.answererData[dataIndex].securityQuestionAnswer
      this.editDialogFormVisible = true
    },
    handleEditSubmit() {
      if (this.answererToOperate.name.length < 1
        ||this.answererToOperate.tele.length != 11) {
        this.$message("请输入合法信息")
        return
      }

      //调用修改答者接口
      modifyAnswerer(this.answererToOperate.id,this.answererToOperate.name,this.answererToOperate.tele,
      this.answererToOperate.securityQuestionContext,this.answererToOperate.securityQuestionAnswer).then((response)=>{
        console.log(response)
        const httpResult = response.data
        if (httpResult.code === 200) {
          this.$message.success('修改成功，即将刷新数据')
          this.editDialogFormVisible = false
          this.searchAnswererByKey()
        } else {
          this.$message.error(httpResult.message)
        }
      })
    },
    handleDelete(index) {
      let dataIndex = index + this.pageSize * (this.currentPage - 1)
      let answererIdToDelete = this.answererData[dataIndex].id
      this.$msgbox.confirm('确认删除此答者吗？', '删除警告', {
        type: 'warning',
        confirmButtonText: '确认删除'
      }).then(() => {
        deleteAnswerer(answererIdToDelete).then((response)=>{
          console.log(response)
          const httpResult = response.data
          if (httpResult.code === 200) {
            this.$message.success('删除成功，即将刷新数据')
            this.searchAnswererByKey()
          } else {
            this.$message.error('删除答者失败')
          }
        })
      })
    },
    handleSelectionChange (val) {
      this.selectedAnswerer = val
      // console.log(val)
    },
    showGroups () {
      if(this.selectedAnswerer.length==0){
        this.$message.warning("未选中答者")
        return
      }

      this.answererNames = []
      for(let i=0;i<this.selectedAnswerer.length;i++){
        this.answererNames.push(this.selectedAnswerer[i].username)
      }

      queryGroupsByKeyword('').then((res) => {
        this.groupData = res.data.data
      })
      this.groupDialogTableVisible = true
    },
    searchGroup () {
      queryGroupsByKeyword(this.group.groupName).then((res) => {
        this.groupData = res.data.data
      })
    },
    addAnswererToGroup (groupName) {
      //调用接口将答者加入到群组
      console.log(this.answererNames)
      console.log(groupName)
      addAnswererToGroup(this.answererNames,groupName).then((response)=>{
        const httpResult = response.data
        if (httpResult.code === 200) {
          this.$message.success('添加到群组成功')
          this.groupDialogTableVisible = false
        } else {
          this.$message.error(httpResult.message)
        }
      })
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
    },
    cleanAnswererBuffer() {
      this.answererToOperate.id = ''
      this.answererToOperate.name = ''
      this.answererToOperate.tele = ''
      this.answererToOperate.password = ''
      this.answererToOperate.securityQuestionAnswer = ''
      this.answererToOperate.securityQuestionContext = ''
    }
  },
  created() {
    this.userInfo = JSON.parse(window.sessionStorage.getItem("data"))
    this.searchAnswererByKey(this.userInfo.id,"")
  }
}
</script>

<style scoped>
.form {
  background-color: white;
  padding: 20px;
  margin-bottom: 20px;
}

.table {
  background: white;
  padding: 20px;
}

.pagination {
  padding-top: 20px;
  text-align: right;
}
</style>
